#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

void MergsortNoR(int* a, int n)
{
	int* tmp = (int*)calloc(n, sizeof(int));
	if (!tmp)
		exit(-1);
	int gap = 1;
	while (gap < n)
	{
		for (int i = 0; i < n; i += 2 * gap)
		{
			int begin1 = i, end1 = i + gap - 1;
			int begin2 = i + gap, end2 = i + 2 * gap - 1;
			int index = i;
			if (begin2 >= n)
				break;
			if (end2 >= n)
				end2 = n - 1;
			while (begin1 <= end1 && begin2 <= end2)
			{
				if (a[begin1] < a[begin2])
					tmp[index++] = a[begin1++];
				else
					tmp[index++] = a[begin2++];
			}
			while (begin1 <= end1)
			{
				tmp[index++] = a[begin1++];
			}
			while (begin2 <= end2)
			{
				tmp[index++] = a[begin2++];
			}
			memcpy(a + i, tmp + i, sizeof(int)*(end2-i+1));
		}
		gap *= 2;
	}
}

void CountSort(int* a, int n)
{
	int min = a[0], max = a[0];
	for (int i = 0; i < n; i++)
	{
		if (a[i] > max)
			max = a[i];
		if (a[i] < min)
			min = a[i];
	}
	int* count = (int*)calloc(max - min + 1, sizeof(int));
	if (!count)
		exit(-1);
	for (int i = 0; i < n; i++)
	{
		count[a[i] - min]++;
	}
	int j = 0;
	for (int i = 0; i < max - min + 1; i++)
	{
		while (count[i]--)
		{
			a[j++] = i + min;
		}
	}
}

void PrintArray(int* a, int n)
{
	for (int i = 0; i < n; i++)
	{
		printf("%d ", a[i]);
	}
}

int main()
{
	int a[] = { 1,3,5,7,9,34,5,76 };
	//MergsortNoR(a, sizeof(a) / sizeof(a[0]));
	CountSort(a, sizeof(a)/sizeof(a[0]));
	PrintArray(a, sizeof(a)/sizeof(a[0]));
}